//
//  ListViewController.m
//  atlas
//
//  Created by 你好 on 16/12/29.
//  Copyright © 2016年 xyxNav. All rights reserved.
//

#import "ListViewController.h"
#import "NavView.h"
#import "RGCardViewLayout.h"
#import "RGCardCollectionViewCell.h"
//#import <MWPhotoBrowser.h>
#import "PhotoBrowser.h"
@interface ListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,MWPhotoBrowserDelegate,RGCardCollectionViewCellDelegate>

@property (nonatomic,retain)UIButton *centerButton;
@property (nonatomic,retain)UIImageView *backImageView;
@property (nonatomic,retain)NavView *navView;
@property (nonatomic,retain)UICollectionView *collectionView;
@property (nonatomic,retain)UILabel *bottomRightLabel;
@property (nonatomic,retain)UILabel *bottomLeftLabel;
@property (nonatomic,strong)PhotoBrowser *photoBrowser;
@property (nonatomic,strong)NSMutableArray *photos;

@end


static NSString *RGcardCollectionViewCell=@"RGCardCollectionViewCell";

@implementation ListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor=[UIColor whiteColor];
    self.photos=[[NSMutableArray alloc]initWithCapacity:0];
    
    NSURL *backImageUrl=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@?token=%@",GETIMAGE_URL,self.photoAlbum.bgImageUrl,[UserManager shareInstance].userToken]];
    self.backImageView=[UIImageView new];
    self.backImageView.contentMode=UIViewContentModeScaleAspectFill;
    self.backImageView.clipsToBounds=YES;
    self.backImageView.userInteractionEnabled=YES;
    [self.view addSubview:self.backImageView];
    [self.backImageView sd_setImageWithURL:backImageUrl placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    
    self.navView=[[NavView alloc]init];
    [self.navView.leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.navView.rightButton setImage:[UIImage imageNamed:@"right_icon"] forState:UIControlStateNormal];
    [self.navView.leftButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView.rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navView.centerLabel.text=self.photoAlbum.name;
    [self.view addSubview:self.navView];
    
    RGCardViewLayout *layout=[[RGCardViewLayout alloc]init];
    self.collectionView=[[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    [self.collectionView registerClass:[RGCardCollectionViewCell class] forCellWithReuseIdentifier:RGcardCollectionViewCell];
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    self.collectionView.backgroundColor=[UIColor colorWithWhite:1 alpha:0.5];
    [self.view addSubview:self.collectionView];
    
    if (self.photoAlbum.photoArray.count>0)
    {
        self.bottomRightLabel=[[UILabel alloc]init];
        self.bottomRightLabel.backgroundColor=[UIColor clearColor];
        self.bottomRightLabel.textAlignment=NSTextAlignmentRight;
        self.bottomRightLabel.textColor=[UIColor blackColor];
        self.bottomRightLabel.text=[NSString stringWithFormat:@"1/%ld",self.photoAlbum.photoArray.count];
        [self.view addSubview:self.bottomRightLabel];
    }
    
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.equalTo(@64);
    }];
    
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.top.equalTo(self.view);
    }];
    
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(self.navView.mas_bottom);
    }];
    
    
    [self.bottomRightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.right.equalTo(self.view).offset(-30);
        make.width.equalTo(@(self.view.bounds.size.width/2-30));
        make.height.equalTo(@50);
    }];

    
    self.bottomLeftLabel=[UILabel new];
    self.bottomLeftLabel.backgroundColor=[UIColor clearColor];
    self.bottomLeftLabel.textAlignment=NSTextAlignmentLeft;
    self.bottomLeftLabel.textColor=[UIColor blackColor];
    self.bottomLeftLabel.text=[NSString stringWithFormat:@"010-80876654"];
    [self.view addSubview:self.bottomLeftLabel];
    
    
    [self.bottomLeftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(30);
        make.bottom.equalTo(self.view);
        make.width.equalTo(@(self.view.bounds.size.width/2-30));
        make.height.equalTo(@50);
    }];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.collectionView reloadData];
}

#pragma mark - <UICollectionDelegate,UICollectionViewDataSource>

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView==self.collectionView)
    {
        double averageWidth = self.collectionView.contentSize.width/self.photoAlbum.photoArray.count;
        int index=scrollView.contentOffset.x/averageWidth;
        self.bottomRightLabel.text=[NSString stringWithFormat:@"%d/%ld",index+1,self.photoAlbum.photoArray.count];
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RGCardCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:RGcardCollectionViewCell forIndexPath:indexPath];
    if (self.sourceFrom==SourceFrom_PhotoAlbum)
    {
        Photo *photo=[self.photoAlbum.photoArray objectAtIndex:indexPath.section];
        [cell configPhotoData:photo];
    }
    else if (self.sourceFrom==SourceFrom_Recommend)
    {
        [cell configRecommendData:self.recommend];
    }
    cell.delegate=self;
  
    return cell;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (self.sourceFrom==SourceFrom_PhotoAlbum)
    {
        return self.photoAlbum.photoArray.count;
    }
    else if (self.sourceFrom==SourceFrom_Recommend)
    {
        return 1;
    }
    return 0;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    return [self.photos objectAtIndex:index];
}

-(void)buttonClick:(UIButton *)button
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)rightButtonClick:(UIButton *)button
{
    self.navigationController.delegate=nil;
    [self.photos removeAllObjects];
    
    [UserDefault setObject:[NSNumber numberWithBool:NO] forKey:ISFROMLISTVC];
    
    if (self.sourceFrom==SourceFrom_PhotoAlbum)
    {
        for (Photo *photo in self.photoAlbum.photoArray)
        {
            NSURL *imageUrl=nil;
            if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
            {
                imageUrl=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@?token=%@",GETIMAGE_URL,photo.imageUrl,[UserManager shareInstance].userToken]];
            }
            else
            {
                imageUrl=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@?token=%@",GETIMAGE_URL,photo.tabletUrl,[UserManager shareInstance].userToken]];
            }
            MWPhoto *p=[MWPhoto photoWithURL:imageUrl];
            [self.photos addObject:p];
        }
    }
    else if (self.sourceFrom==SourceFrom_Recommend)
    {
        NSURL *imageUrl=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@?token=%@",GETIMAGE_URL,self.recommend.imageUrl,[UserManager shareInstance].userToken]];
        MWPhoto *p=[MWPhoto photoWithURL:imageUrl];
        [self.photos addObject:p];
    }
    
    
    BOOL displayActionButton = YES;
    BOOL displaySelectionButtons = NO;
    BOOL displayNavArrows = NO;
    BOOL enableGrid = NO;
    BOOL startOnGrid = NO;
    BOOL autoPlayOnAppear = NO;
    
    self.photoBrowser = [[PhotoBrowser alloc] initWithDelegate:self];
    self.photoBrowser.photoAlbum=self.photoAlbum;
    self.photoBrowser.displayActionButton = displayActionButton;
    self.photoBrowser.displayNavArrows = displayNavArrows;
    self.photoBrowser.displaySelectionButtons = displaySelectionButtons;
    self.photoBrowser.alwaysShowControls = displaySelectionButtons;
    self.photoBrowser.zoomPhotosToFill = NO;
    self.photoBrowser.enableGrid = enableGrid;
    self.photoBrowser.startOnGrid = startOnGrid;
    self.photoBrowser.enableSwipeToDismiss = NO;
    self.photoBrowser.autoPlayOnAppear = autoPlayOnAppear;
    [self.photoBrowser setCurrentPhotoIndex:0];
    [self.navigationController pushViewController:self.photoBrowser animated:YES];
    
}


- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [self.collectionView performBatchUpdates:^{
            [self.collectionView setCollectionViewLayout:self.collectionView.collectionViewLayout animated:YES];
        } completion:^(BOOL finished) {
            [self.collectionView reloadData];
        }];
    }];
}


//我们看到第二个参数coordinator，它的类型是UIViewControllerTransitionCoordinator，它能响应VC转换进度，并且提供了以下方法：
- (BOOL)animateAlongsideTransition:(void (^)(id<UIViewControllerTransitionCoordinatorContext> context))animation
                        completion:(void (^)(id<UIViewControllerTransitionCoordinatorContext> context))completion
{
    return YES;
}


#pragma mark - RGCardCollectionViewCellDelegate

-(void)doubleClickCell:(RGCardCollectionViewCell *)cell
{
    if (((RGCardViewLayout *)self.collectionView.collectionViewLayout).isFullScreen)
    {
        ((RGCardViewLayout *)self.collectionView.collectionViewLayout).isFullScreen=NO;
        [self.collectionView reloadData];
    }
    else
    {
        ((RGCardViewLayout *)self.collectionView.collectionViewLayout).isFullScreen=YES;
        [self.collectionView reloadData];
    }
}

#pragma mark

- (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0)
{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0)
{
    return self.prevViewController.supportedInterfaceOrientations;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0)
{
    return self.prevViewController.preferredInterfaceOrientationForPresentation;;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
